//
//  CPJaonUtil.swift
//  BabaLink
//
//  Created by wrs on 2018/8/14.
//  Copyright © 2018年 wrs. All rights reserved.
//

import Foundation

public func converObjToJson(obj: Any) -> String? {
    if let data = try? JSONSerialization.data(withJSONObject: obj, options: .prettyPrinted) {
       return String(data: data, encoding: String.Encoding.utf8)
    } else {
        return nil
    }
}

public func converJsonToObj(json: String) -> Any? {
    if let data = json.data(using: String.Encoding.utf8) {
        if let obj = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers) {
            return obj
        } else {
            return nil
        }
    } else {
        return nil
    }
}

public func dataToModel<T>(_ type: T.Type, from data: Data) throws -> T where T : Decodable {
    return try JSONDecoder().decode(type, from: data)
}
